package com.droid.mvvmlib.base;

import android.app.Application;

import com.droid.mvvmlib.databinding.BaseBindingQuickAdapter;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.lifecycle.MutableLiveData;

/**
 * 分页ViewModel
 *
 * @author zyc0617
 * @since 2019/8/18 15:35
 */
public class BasePagingViewModel<M extends BasePagingModel, D> extends UiChangeViewModel<M, D> implements BasePagingModel.IModelListener<ArrayList<D>> {

    public final MutableLiveData<ObservableArrayList<D>> dataList = new MutableLiveData<>();
    public MutableLiveData<BaseBindingQuickAdapter> adapter = new MutableLiveData<>();

    public BasePagingViewModel(@NonNull Application application, M model) {
        super(application, model);
        dataList.setValue(new ObservableArrayList<>());
        if (model != null) {
            model.register(this);
        }
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (model != null) {
            model.unRegister(this);
        }
    }

    @Override
    public void tryToRefresh() {
        super.tryToRefresh();
    }

    @Override
    public void onLoadFinish(BasePagingModel model, ArrayList<D> data, boolean isEmpty, boolean isRefresh, boolean isNextPage) {
        if (model == this.model) {
            if (isRefresh) {
                dataList.getValue().clear();
            }
            if (isEmpty) {
                if (isRefresh) {
                    viewStatus.setValue(ViewStatus.EMPTY);
                } else {
                    viewStatus.setValue(ViewStatus.NO_MORE_DATA);
                }
            } else {
                dataList.getValue().addAll(data);
                viewStatus.setValue(ViewStatus.SHOW_CONTENT);
            }
        }

    }

    @Override
    public void onLoadFail(BasePagingModel model, String error, boolean isRefresh) {
        errorMessage.setValue(error);
        if (isRefresh) {
            viewStatus.setValue(ViewStatus.REFRESH_ERROR);
        } else {
            viewStatus.setValue(ViewStatus.LOAD_MORE_FAILED);
        }

    }
}
